package com.itfreer.gis.server.geoserver;

import java.io.File;

import io.minio.MinioClient;
import io.minio.policy.PolicyType;

/**
 * 定义GeoServer WMTS切片数据上传代码
 */
public class GeoServerWMTSConvert {

	private String wmtsBucket = "wmts";
	private String wmtsBasePath = "/Volumes/work/data/itfeer_XYC/";
	private String wmtsName = "xyc";

	public void uploader() {
		try {
			File baseFile = new File(wmtsBasePath);
			// 1、层级
			File[] cjList = baseFile.listFiles();
			if (cjList == null) {
				return;
			}

			// 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
			MinioClient minioClient = new MinioClient("http://47.106.79.19:9000", "minio", "123!@#qweQWE@ITFREER");

			// 检查存储桶是否已经存在
			boolean isExist = minioClient.bucketExists(wmtsBucket);
			if (!isExist) {
				// 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
				minioClient.makeBucket(wmtsBucket);
				minioClient.setBucketPolicy(wmtsBucket, "*", PolicyType.READ_WRITE);
			}

			for (File cj : cjList) {
				String cjName = cj.getName();
				String[] cjs = cjName.split("_");
				if (cjs.length != 3) {
					continue;
				}
				String cjn = cjs[cjs.length - 1];
				Integer cji = Integer.parseInt(cjn);

				// 2、空目录
				File[] knList = cj.listFiles();
				if (knList != null) {
					for (File kn : knList) {
						// 3、图片
						File[] pngList = kn.listFiles();
						if (pngList != null) {
							for (File pngFile : pngList) {
								String[] pngs = pngFile.getName().split("_");
								String[] hz = pngs[1].split("\\.");
								Integer x = Integer.parseInt(pngs[0]);
								Integer y = Integer.parseInt(hz[0]);
								String key = wmtsName + "/" + cji.toString() + "/" + x.toString() + "/" + y.toString()
										+ "." + hz[1];

								minioClient.putObject(wmtsBucket, key, pngFile.getPath(), "image/png");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			System.out.println("Error occurred: " + e);
		}
	}

}
